package com.cmd.project.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.cmd.common.utils.StringUtils;
import com.cmd.project.vo.AreaVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author cq
 * @date 2024/11/14
 */
@Service
public class AreaServiceImpl {

    @Autowired
    private JdbcTemplate jdbctemplate;

    public List<AreaVo> getArea() {

        String sql = "select area_code as areaCode,area_name as value,area_name as label,parent_code as parentCode " +
                " from sys_area where status =0";
        List<Map<String, Object>> maps = jdbctemplate.queryForList(sql);
        List<AreaVo> areaVos = CollUtil.newArrayList();
        maps.forEach(map -> {
            AreaVo areaVo = new AreaVo();
            BeanUtil.copyProperties(map, areaVo);
            areaVos.add(areaVo);
        });
        return buildAreaTree(areaVos);
    }

    public List<AreaVo> buildAreaTree(List<AreaVo> lists) {
        List<AreaVo> returnList = CollUtil.newArrayList();
        List<String> tempList = lists.stream().map(AreaVo::getAreaCode).collect(Collectors.toList());
        for (AreaVo areaVo : lists) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(areaVo.getParentCode())) {
                recursionFn(lists, areaVo);
                returnList.add(areaVo);
            }
        }
        if (returnList.isEmpty()) {
            returnList = lists;
        }
        return returnList;
    }

    private void recursionFn(List<AreaVo> list, AreaVo t) {
        // 得到子节点列表
        List<AreaVo> childList = getChildList(list, t);
        t.setChildren(childList);
        for (AreaVo tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    private boolean hasChild(List<AreaVo> list, AreaVo t) {
        return getChildList(list, t).size() > 0;
    }

    private List<AreaVo> getChildList(List<AreaVo> list, AreaVo t) {
        List<AreaVo> tlist = new ArrayList<AreaVo>();
        Iterator<AreaVo> it = list.iterator();
        while (it.hasNext()) {
            AreaVo n = it.next();
            if (StringUtils.isNotEmpty(n.getParentCode()) && n.getParentCode().equals(t.getAreaCode())) {
                tlist.add(n);
            }
        }
        return tlist;
    }
}
